<template>
	<view class="u-p-l-30 u-p-r-30">
		<u-form labelWidth="65" :model="formData" ref="form">
			<u-form-item :borderBottom="true" prop="name" label="昵称" required="">
				<u-input required border="none" type="text" v-model="formData.name" placeholder="请输入昵称"></u-input>
			</u-form-item>
		</u-form>
		<button @click="submit" :style="[inputStyle]" class="getCaptcha u-m-t-30">修改</button>
	</view>
</template>

<script>
	let access_token,info;
	export default {
		data() {
			return {
				formData: {
					name: ''
				},
				rules: {
					name: [{
							type: 'string',
							required: true,
							message: '请输入昵称',
							trigger: ['blur', 'change']
						},
						{
							min: 3,
							max: 8,
							message: '昵称长度在 3 到 10 之间',
							trigger: ['blur', 'change']
						},
						{
							pattern: /^[0-9a-zA-Z\u4e00-\u9fa5]*$/g,
							// 正则检验前先将值转为字符串
							transform(value) {
								return String(value);
							},
							message: '昵称只能包含字母、数字、中文',
							trigger: ['blur', 'change']
						}
					]
				}
			}
		},
		async onLoad() {
			if (!uni.$u.utils.isLogin()) {
				return;
			}
			info = uni.getStorageSync('userinfo');
			access_token = uni.getStorageSync('access_token');
			console.log(info);
			this.formData.name = info.name;
		},
		onReady() {
			// 需要在onReady中设置规则
			this.$refs.form.setRules(this.rules)
		},
		computed: { //计算属性
			inputStyle() {
				let style = {};
				if (this.formData.name) {
					style.color = "#fff";
					style.backgroundColor = this.$u.color['warning'];
				}
				return style;
			}
		},
		methods: {
			async submit() {
				this.$refs.form.validate().then(() => {
					//调用API，更新昵称
					this.update();
				}).catch(err => {
					uni.$u.toast('表单错误信息：' + err);
				})
			},
			async update() {
				let res = await uni.$u.http.put('/api/user', {
					name: this.formData.name
				}, {
					header: {
						Authorization: 'bearer ' + access_token
					}
				})
				if(res !== false){
					uni.$u.toast('更新个人信息成功');
					//更新缓存里的昵称
					info.name = this.formData.name;
					uni.setStorageSync('userinfo',info);
					//getApp().globalData.mqc = info.name;
				}			
				
			}
			
		}
	}
</script>

<style>

</style>
